#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

#define NUM 1024
#define SIZE 100

//#define Debug 1 

char cwd[1024];
int lastcode = 0;
const char* getUsername()
{
    const char* name = getenv("USER");
    if(name) return name;
    else return "none";
}
const char* getHostname()
{
    const char* host = getenv("HOSTNAME");
    if(host) return host;
    else return "none";
}
const char* getCwd()
{
    const char* cwd = getenv("PWD");
    if(cwd) return cwd;
    else return "none";
}

int getUsercommand(char * command,int num)
{
    printf("[%s@%s %s]#",getUsername(),getHostname(),getCwd());
    // scanf("%s",usercommand);
    char*r =  fgets(command, num ,stdin);
    if(r == NULL) return -1; //todo
    //"abc\n" 去掉\n  "\n"不会越界 
    command[strlen(command) - 1] = '\0';
    return strlen(command);
}

void commandSplit(char* in ,char** out)
{
    int argc = 0;
    out[argc++] = strtok(in," ");
    while(out[argc++] = strtok(NULL," "));
#ifdef Debug
    for(int i = 0;out[i];i++)
    {
        printf("%d: %s\n",i,out[i]);
    }
#endif 
}

void cd(const char* path)
{
    chdir(path); //修改工作路径
    char tmp[1024];
    getcwd(tmp,sizeof(tmp));
    sprintf(cwd,"PWD=%s",tmp);
    putenv(cwd);
}


// 1-yes  0-no
int doBuildin(char* argv[])
{
    if(strcmp(argv[0],"cd") == 0)
    {
        const char* path = NULL;
        if(argv[1] == NULL) path = ".";
        else path = argv[1];
        cd(path);
        return 1;
    }
    else if(strcmp(argv[0],"echo") == 0) //echo $PWD
    {
        char* val = argv[1] + 1;
        if(argv[1] == NULL)
        {
            printf("\n");
        }
        else if(strcmp(val,"?") == 0)
        {
            printf("%d\n",lastcode);
        }
        else
        {
            printf("%s\n",getenv(val));
        }
        return 1;
    }
    return 0;
}

int execute(char* argv[])
{
    pid_t id = fork();
    if(id < 0) return -1;
    else if(id == 0)
    {
        //exec command
        execvp(argv[0],argv);
        exit(0); //子进程运行结束直接退出 
    }
    else
    {
        int status = 0;
       int rid =  waitpid(-1,&status,0);
       if(rid < 0) return 1;
       else if(rid > 0)
        {
             lastcode = WEXITSTATUS(status);
        }
    }
    return 0;
}


int main()
{
    while(1)
    {
        //1.打印字符串 && 获取用户字符串
        char usercommand[NUM];
        char* argv[SIZE];
        int n =  getUsercommand(usercommand,sizeof usercommand);
        if(n <= 0) continue; //输入失败 && NULL ----> 重新输入
        //2.分割字符串
        commandSplit(usercommand,argv);
        //3.内键命令check + execute 
        int i = doBuildin(argv); 
        if(i) continue; //重新输入
        //4.执行命令
        execute(argv);
    }
    return 0;
}
